package service

import (
	"context"
	"github.com/astaxie/beego"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"io"
)

func config() storage.Config {
	cfg := storage.Config{}

	cfg.Zone = &storage.ZoneHuabei
	// 是否使用https域名
	cfg.UseHTTPS = false
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false

	return cfg
}



func Upload(localFile io.Reader, size int64, filename string) (string, error) {
	bucket := beego.AppConfig.String("qiniu::bucket")
	accessKey := beego.AppConfig.String("qiniu::accessKey")
	secretKey := beego.AppConfig.String("qiniu::secretKey")

	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}

	mac := qbox.NewMac(accessKey, secretKey)
	upToken := putPolicy.UploadToken(mac)

	cig := config()

	formUploader := storage.NewFormUploader(&cig)

	ret := storage.PutRet{}

	putExtra := storage.PutExtra{}

	err := formUploader.Put(context.Background(), &ret, upToken, filename, localFile, size, &putExtra)

	if err != nil {
		return "", err
	}

	return ret.Key, nil
}

